﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using shfa.snomtastic.systray.components;
using System.Reflection;
using System.Drawing;
using System.Threading;
using System.Diagnostics;
using System.Net.Security;
using Microsoft.Office.Interop.UccApi;

namespace shfa.snomtastic.systray
{
    public partial class MainApplication
    {
        private TaskbarNotifier tbMain;
        private TaskButton tsPhone;
        private TaskButton tsClose;

        private UserService.UserPhoneInfo userPhone;
        private uccInfo ucc;
        private WindowManager wmMain;
        private Thread thHiding;
        private AboutToast aboutToast;

        private Font fDefaultFont;
        private Font fCallerFont;


        public void InitToast()
        {

            // Main Toast
            userPhone = getUserPhone();
            if (userPhone != null)
            {
                initUcc();
                BuildToast();
                initWindowManager();
            }



        }

        private UserService.UserPhoneInfo getUserPhone()
        {
            UserService.user RemoteUserService = new ClientUserService();
            try
            {
                return RemoteUserService.getUserPhoneInfo(userSID);
            }
            catch
            {
                return null;
            }

        }

        private void InitAbout()
        {
            aboutToast = new AboutToast();
        }

        private void initUcc()
        {
            ucc = new uccInfo(userPhone.LoginName, userPhone.LoginPass, userPhone.Domain, userPhone.OcsServer, userPhone.Transport, userPhone.UriName);
            ucc.onSessionStart += new EventHandler(ucc_onSessionStart);
            ucc.onSessionEnd += new EventHandler(ucc_onSessionEnd);
        }

        private void initWindowManager()
        {

            wmMain = new WindowManager();
        }

        private void BuildToast()
        {

            Assembly asm = Assembly.GetExecutingAssembly();
            Color transColor = Color.FromArgb(255, 0, 255);

            tbMain = new TaskbarNotifier();

            fDefaultFont = new Font(FontFamily.GenericSansSerif, 9);
            fCallerFont = new Font(fDefaultFont, FontStyle.Bold);
            
            Bitmap b = new Bitmap(asm.GetManifestResourceStream("shfa.snomtastic.systray.images.toasterbkg.bmp"));
            tbMain.SetBackgroundBitmap(b, transColor);



            tsPhone = new TaskButton(
                new Bitmap(asm.GetManifestResourceStream("shfa.snomtastic.systray.images.PhoneUp.bmp")),
                new Bitmap(asm.GetManifestResourceStream("shfa.snomtastic.systray.images.PhoneDown.bmp")),
                new Bitmap(asm.GetManifestResourceStream("shfa.snomtastic.systray.images.PhoneOver.bmp")))
            {
                Left = 1,
                Top = 1,
                ForeColor = Color.FromArgb(42, 61, 88)

            };
            tsPhone.Click += new EventHandler(tsPhone_Click);



            tsClose = new TaskButton(
                new Bitmap(asm.GetManifestResourceStream("shfa.snomtastic.systray.images.CloseUp.bmp")),
                new Bitmap(asm.GetManifestResourceStream("shfa.snomtastic.systray.images.CloseDown.bmp")),
                new Bitmap(asm.GetManifestResourceStream("shfa.snomtastic.systray.images.CloseOver.bmp")))
            {
                Left = 291,
                Top = 2,
                Height = 16,
                Width = 16

            };

            tsClose.Click += new EventHandler(tsClose_Click);

            tbMain.Controls.Add(tsPhone);
            tbMain.Controls.Add(tsClose);

            tbMain.KeepVisibleOnMousOver = false;
            tbMain.ReShowOnMouseOver = false;

        }



        #region Events

        protected void ucc_onSessionEnd(object sender, EventArgs e)
        {
            tbMain.Fade();
            if (thHiding != null && thHiding.IsAlive)
            {
                thHiding.Abort();
            }

        }

        protected void ucc_onSessionStart(object sender, EventArgs e)
        {

            RegSettings rs = new RegSettings();

            HideToastInfo.HideToastModeType modeComm = rs.hideCommunicatorToastMode();
            HideToastInfo.HideToastModeType modeSnom = rs.hideSnomtasticToastMode();

            bool hideComm = false;

            switch (modeComm)
            {
                case HideToastInfo.HideToastModeType.Never:
                    // do nothing
                    break;
                case HideToastInfo.HideToastModeType.Always:
                    hideComm = true;
                    break;
                case HideToastInfo.HideToastModeType.Busy:
                    switch (ucc.Availability.State)
                    {
                        case PresenceStateInfo.PresenceStateType.Busy:
                        case PresenceStateInfo.PresenceStateType.BusyIdle:
                        case PresenceStateInfo.PresenceStateType.DoNotDisturb:
                            hideComm = true;
                            break;
                        default:
                            // do nothing
                            break;
                    }
                    break;
                default:
                    break;
            }

            if (hideComm)
            {
                thHiding = new Thread(new ThreadStart(wmMain.HideWindow));
                thHiding.Start();
            }


            switch (modeSnom)
            {
                case HideToastInfo.HideToastModeType.Never:
                    showToast();
                    break;
                case HideToastInfo.HideToastModeType.Always:
                    // do nothing
                    break;
                case HideToastInfo.HideToastModeType.Busy:
                    switch (ucc.Availability.State)
                    {
                        case PresenceStateInfo.PresenceStateType.Busy:
                        case PresenceStateInfo.PresenceStateType.BusyIdle:
                        case PresenceStateInfo.PresenceStateType.DoNotDisturb:
                            // do nothing
                            break;
                        default:
                            showToast();
                            break;
                    }
                    break;
                default:
                    break;
            }

            // showToast();
        }

        protected void tsClose_Click(object sender, EventArgs e)
        {
            tbMain.Fade();
        }

        protected void tsPhone_Click(object sender, EventArgs e)
        {
            PhoneOffHook();
            tbMain.Fade();
        }

        #endregion

        #region helpers
        private void PhoneOffHook()
        {
            ServicePointManager.ServerCertificateValidationCallback +=
                    delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                    { return true; };

            WebRequest req = HttpWebRequest.Create("https://" + userPhone.PhoneIp + "/command.htm?key=SPEAKER");
            NetworkCredential nc = new NetworkCredential(userPhone.Http_User, userPhone.Http_Pass);
            req.PreAuthenticate = true;
            req.Credentials = nc;
            try
            {
                req.GetResponse();
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                Debug.Print(s);
            }
        }

        private void showToast()
        {
            List<TextItem> tList = new List<TextItem>();
            
            tList.Add(new TextItem(ucc.Caller.Uri.User, fCallerFont, Color.FromArgb(42, 61, 88), new Point(44, 4)));
            tList.Add(new TextItem("Click here to answer on handset.", fDefaultFont, Color.FromArgb(42, 61, 88), new Point(44, 29)));

            tsPhone.TextItems = tList;

            if (tbMain.TaskbarState == TaskbarNotifier.TaskbarStates.hidden)
                tbMain.Show(250, 3000, 250);

        }


        private void showAbout()
        {
            AssemblyInfo ai = new AssemblyInfo();
            aboutToast.Show(
                ai.AssemblyTitle + " " + ai.AssemblyVersion.Major.ToString() + "." + ai.AssemblyVersion.Minor.ToString(),
                ai.AssemblyProduct,
                ai.AssemblyDescription,
                userName,
                (userPhone != null) ? userPhone.PhoneIp : "",
                lastCheck);

            ai = null;
        }

        #endregion

    }
}
